import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {getQueryString} from '../utils/util';
import { Flex } from 'antd-mobile';
import { PullToRefresh, ListView, SearchBar, NavBar, Icon, List, Drawer} from 'antd-mobile';

import 'antd-mobile/lib/flex/style/index.css';
import 'antd-mobile/lib/search-bar/style/index.css';
import 'antd-mobile/lib/pull-to-refresh/style/index.css';
import 'antd-mobile/lib/list-view/style/index.css';
import 'antd-mobile/lib/nav-bar/style/index.css';
import 'antd-mobile/lib/icon/style/index.css';
import 'antd-mobile/lib/list/style/index.css';
import 'antd-mobile/lib/drawer/style/index.css';
import '../static/styles/taoke.css';

import Goods from '../components/goods';
import Slide from '../components/slide';

import loadIcon from '../static/icon/load.gif';

import { get } from '../api/getData';

let pageIndex = 1;
let index = 0;

let initListViewSize = 20;

function genData(obj, refreshing=false, isLoading=false, pIndex = 1) {
    let reqParams = {
        page:pIndex,
        length:20,
        ...obj.state.search
    };

    get('/api/goods/list', reqParams, function (error, data) {
        if(null === error){
            console.log(data.data.length);
            if(data.error === undefined){
                if(pIndex > 1){
                    obj.rData = [...obj.rData, ...data.data];
                    obj.setState({
                        data : obj.state.data.concat(data.data)
                    });
                }else {
                    obj.rData = data.data;
                    obj.setState({
                        data : data.data
                    });
                    ReactDOM.findDOMNode(obj.lv).scrollTop = 0;
                }

                if(data.data.length === 0){
                    obj.setState({
                        hasMore : false
                    })
                }

                obj.setState({
                    dataSource: obj.state.dataSource.cloneWithRows(obj.rData),
                    refreshing: refreshing,
                    isLoading: !isLoading
                });
            }
        }
    });
}

class Taoke extends Component {
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        this.rData = [];

        let searchKey = getQueryString('searchKey');

        let searchStyle = {right:'-1000px'};
        if(searchKey && searchKey.length > 0){
            searchStyle = {right:'0'};
        }

        this.state = {
            dataSource,
            refreshing: true,
            isLoading: true,
            height: document.documentElement.clientHeight,
            useBodyScroll: false,
            data : [],
            searchStyle : searchStyle,
            open : false,
            search:{cid:getQueryString('cid'),searchKey:searchKey},
            category:[],
            hasMore:true,
            searchKey : searchKey?searchKey:'',
        };


    }

    componentDidUpdate() {
        if (this.state.useBodyScroll) {
            document.body.style.overflow = 'auto';
        } else {
            document.body.style.overflow = 'hidden';
        }
    }

    componentWillMount(){
        let __this = this;
        get('/api/category', {}, function (error, data) {
            if(null === error){
                if(data.error === undefined){
                    __this.setState({
                        category: data
                    });
                }
            }
        });
    }

    componentWillUnmount(){
        window.sessionStorage.setItem('list-cache', JSON.stringify(this.state));
    }

    componentDidMount() {
        if(window.sessionStorage.getItem('list-cache') !== null) {
            let stateData = JSON.parse((window.sessionStorage.getItem('list-cache')));
            this.rData = stateData.data;
            initListViewSize = stateData.data.length;
            this.setState({
                dataSource : this.state.dataSource.cloneWithRows(stateData.data),
                refreshing: stateData.refreshing,
                isLoading: stateData.isLoading,
                height: stateData.height,
                useBodyScroll: stateData.useBodyScroll,
                data : stateData.data,
                searchStyle : stateData.searchStyle,
                open : stateData.open,
                search:stateData.search,
                category:stateData.category,
                hasMore:stateData.hasMore,
                searchKey : stateData.searchKey?stateData.searchKey:'',
            } , function () {
                let scrollTopValue = window.sessionStorage.getItem('scroll-top-cache') ? window.sessionStorage.getItem('scroll-top-cache') : 0;
                ReactDOM.findDOMNode(this.lv).scrollTop = scrollTopValue;

                window.sessionStorage.removeItem('list-cache');
                window.sessionStorage.removeItem('scroll-top-cache');
            });

        }else {
            const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop;

            this.setState({
                height: hei,
            } , function () {
                genData(this);
            });
        }


        document.title = '海量优惠券免费领';
    }

    onScroll(e){
        window.sessionStorage.setItem('scroll-top-cache', e.target.scrollTop);
    }

    onRefresh = () => {
        this.setState({ refreshing: false, isLoading: false } , function () {
            genData(this, false, false);
        });
    };

    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        this.setState({ isLoading: true ,refreshing: false} ,function () {
            genData(this, false, true, ++pageIndex);
        });
    };

    onOpenChange = () => {
        this.setState({ open: !this.state.open });
    };

    showSearch = () => {
        this.manualFocusInst.focus();
        this.setState({
            searchStyle:{
                right:'0'
            }
        });
    };

    hideSearch = () => {
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:null},
            refreshing: false,
            isLoading: true,
            searchKey:'',
            searchStyle:{
                right:'-1000px'
            }
        }, genData.bind(this, this, false, true));
    };

    reqCategory(cid) {
        pageIndex = 1;
        this.setState({
            search : {cid:cid,searchKey:''},
            refreshing: false,
            isLoading: true,
            open:false,
        }, genData.bind(this, this, false, false));
    };

    submitSearch(){
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:this.state.searchKey},
            refreshing: false,
            isLoading: true
        }, genData.bind(this, this, false, true));
    }

    searchValueChange(value){
        this.setState({ searchKey: value});
    }

    searchValueClear(){
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:null},
            refreshing: false,
            isLoading: true,
            searchKey:'',
            searchStyle:{
                right:'-1000px'
            }
        }, genData.bind(this, this, false, true));
    }

    render() {
        const row = (rowData, sectionID, rowID) => {

            if(rowID % 2 !== 0) {
                return (
                    <div className="list-view-item ml10" key={rowID}>
                        <Goods className="bf" showOldPrice="1"  data={rowData}/>
                    </div>
                );
            }else{
                return (
                    <div className="list-view-item " key={rowID}>
                        <Goods className="bf" showOldPrice="1"  data={rowData}/>
                    </div>
                );
            }


        };

        const sidebar = (<List>
            {this.state.category.map((item, index) => {
                return (<List.Item key={index} onClick={this.reqCategory.bind(this, item.id)}
                >{item.category_name}</List.Item>);
            })}
        </List>);

        return (
            <div style={{overflowX:'hidden'}}>
                <NavBar
                    icon={<Icon type="ellipsis" />}
                    onLeftClick={this.onOpenChange}
                    rightContent={[
                        <Icon key="0" onClick={this.showSearch.bind(this)} type="search" style={{ marginRight: '16px' }} />
                    ]}
                >
                    优惠券精选
                </NavBar>
                <SearchBar
                    value={this.state.searchKey}
                    placeholder="输入你想找的"
                    style={this.state.searchStyle}
                    maxLength={30}
                    ref={ref => this.manualFocusInst = ref}
                    onCancel={this.hideSearch}
                    onSubmit={this.submitSearch.bind(this)}
                    onChange={this.searchValueChange.bind(this)}
                    onClear={this.searchValueClear.bind(this)}
                />

                <Drawer
                    className="drawer"
                    sidebar={sidebar}
                    enableDragHandle
                    open={this.state.open}
                    onOpenChange={this.onOpenChange}
                >
                    {/*<Slide/>*/}
                    <div className="box">
                        <Flex className="pdb15 box-item">
                            <ListView
                                key={this.state.useBodyScroll ? '0' : '1'}
                                ref={el => this.lv = el}
                                dataSource={this.state.dataSource}
                                renderFooter={() => (<div style={{ textAlign: 'center' }}>
                                    {this.state.isLoading ? '刷新中...' : this.state.hasMore ? '上拉刷新' : '没有更多了'}
                                </div>)}
                                renderRow={row}
                                useBodyScroll={this.state.useBodyScroll}
                                style={this.state.useBodyScroll ? {} : {
                                    height: this.state.height,
                                    textAlign:'center'
                                }}
                                pullToRefresh={<PullToRefresh
                                    refreshing={this.state.refreshing}
                                    onRefresh={this.onRefresh}
                                    indicator={{activate : <div className="list-view-indicator"><img src={loadIcon} alt=""/></div>, deactivate : <div className="list-view-indicator">下拉刷新</div>, release : <div className="list-view-indicator">下拉刷新</div>, finish : <div></div>}}
                                />}
                                onEndReached={this.onEndReached}
                                pageSize={20}
                                initialListSize={initListViewSize}
                                onScroll={this.onScroll}
                            />
                        </Flex>
                    </div>
                </Drawer>
            </div>
        );
    }
}

export default Taoke;
